package com.isoftstone.securityframework.device;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.session.mgt.WebSessionKey;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.isoftstone.securityframework.api.crypt.CryptUtil;
import com.isoftstone.securityframework.api.crypt.DESDecrypt;
import com.isoftstone.securityframework.api.crypt.DESEncrypt;

public class DeviceDiscriminateFilter implements Filter {

	private static final String AUTHORIZATION_HEADER="Authorization";
	

	private DESEncrypt desEncrypt = new DESEncrypt();
	private DESDecrypt desDecrypt = new DESDecrypt();
	
	private Logger logger = LoggerFactory.getLogger(DeviceDiscriminateFilter.class);
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	
	/**
	 * 设备接入filter
	 * 1.拦截设备接入请求，产生序列号，保存一条临时记录
	 * 2.返回加密因子
	 * 3.SDK根据因子对设备信息进行加密，重新发送
	 * 4.再次拦截设备接入请求，对信息进行解密，执行controller接入业务
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		//获取设备id
		String authenticate = WebUtils.toHttp(request).getHeader(AUTHORIZATION_HEADER);
		String key = null;
		try {
			//第一次请求
			if(authenticate == null || "".equals(authenticate)){
				//生成加密因子
				key = desEncrypt.initKey();
				HttpSession session = WebUtils.toHttp(request).getSession(true);
				session.setAttribute("key", key);
				//返回cookie和加密因子
				WebUtils.toHttp(response).setHeader("Set-Cookie", "JSESSIONID=" + session.getId());
				WebUtils.toHttp(response).setHeader("www-Authenticate", key);
				WebUtils.toHttp(response).sendError(1111);
				response.getOutputStream().print("");
			}
			// 第二次请求
			if(authenticate != null || !"".equals(authenticate)){
				Cookie[] cookies = WebUtils.toHttp(request).getCookies();
				for (Cookie cookie : cookies) {
					if (cookie.getName().equalsIgnoreCase("jsessionid")) {
						Session session = SecurityUtils.getSecurityManager().getSession(new WebSessionKey(cookie.getValue(),request,response));
						key = session.getAttribute("key").toString();
//						String deviceId = CryptUtil.encodeBytes(desDecrypt.decrypt(authenticate.getBytes(), key));

						//获取设备信息
						InputStream is = request.getInputStream();
						Reader rd = new InputStreamReader(is,"utf-8");
						StringWriter sw = new StringWriter();
						char[] buf = new char[100];
						int length=0;
						while((length=rd.read(buf)) > 0){
							sw.write(buf,0,length);
						}
						sw.close();
						rd.close();
						is.close();
						String deviceProperties = sw.toString();
						deviceProperties = CryptUtil.encodeBytes(desDecrypt.decrypt(deviceProperties.getBytes(), key));
						Device d = new com.isoftstone.securityframework.device.domain.Device();
						request.setAttribute("device", d);
						chain.doFilter(request, response);
						
						//给终端返回系统编号
						session.setAttribute("random", (int)Math.abs(Math.random()*10000));
					}
				}

			}
			
		} catch (Exception e) {
			logger.error("",e);
		}
	}

	@Override
	public void destroy() {

	}
}

